import store from '@/store'
import {
    batteryTypeList
} from './coreData.js'
var encoding = require("./encoding.js")
export function parseBLEData(characteristic) {
    // console.log('parseBLEData in', characteristic)
    // 假设数据是一个ArrayBuffer，首先将其转换为Uint8Array
    const uint8Array = new Uint8Array(characteristic.value);
    let dataView = new DataView(characteristic.value);
    let head = dataView.getUint8(0);
    let cmd = dataView.getUint8(2);

    if (head === 0x89) {
        let update = new Object()
        switch (cmd) {
        case 0x01:
            let voltage = dataView.getUint16(3) / 100; // 电压
            let range = dataView.getUint16(5) / 100; // 里程
            range = range.toFixed(2);
            let temperature = dataView.getUint16(7) / 10; // 温度
            let batteryPercentage = dataView.getUint8(9); // 电量百分比
            update = {
                voltage,
                range,
                temperature,
                batteryPercentage
            }
            break;
        case 0x02:
            let packBatteryCount = dataView.getUint8(3); // 电池串数
            let vehicleType = dataView.getUint8(4); // 车型选择
            let batteryCapacity = dataView.getUint8(5); // 电池容量
            let consumption = dataView.getUint32(6) / 100; // 百公里电耗
            let vehicleTypeName = getModelName('vehicleType', vehicleType)
            update = {
                packBatteryCount,
                vehicleType,
                vehicleTypeName,
                batteryCapacity,
                consumption
            }
            break;
        case 0x03:
            //蓝牙名称
            const bluetoothName = String.fromCharCode.apply(null, uint8Array.slice(3, -1));
            update = {
                bluetoothName
            }
            break;
        case 0x04:
            //软件版本
            const softwareVersion = String.fromCharCode.apply(null, uint8Array.slice(3, -1));
            update = {
                softwareVersion
            }
            break;
        case 0x07:
            //硬件版本
            const hardwareVersion = String.fromCharCode.apply(null, uint8Array.slice(3, -1));
            update = {
                hardwareVersion
            }
            break;
        case 0x0b:
            //车型支持枚举
            const typeVal = dataView.getUint8(3);
            const buffer = Buffer.from(uint8Array.slice(4, -1)); // 这是 "你好" 的 UTF-8 编码
            // 将 Buffer 转换为字符串
            const typeLabel = buffer.toString('utf8');
            store.dispatch('battery/setVehicleTypeData', {
                value: typeVal,
                label: typeLabel
            })
            let batteryData = store.getters['battery/batteryData']
            if (batteryData.vehicleType == typeVal) {
                store.dispatch('battery/setBatteryData', {
                    vehicleTypeName: typeLabel,
                })
            }
            console.log('车型' + typeVal, typeLabel)
            console.log('车型数组', uint8Array.slice(4, -1))
            break;
        case 0x0f:
            //电池类型
            const batteryType = dataView.getUint8(3);
            let batteryTypeName = getModelName('batteryType', batteryType)
            console.log('电池类型:' + batteryType)
            update = {
                batteryType,
                batteryTypeName
            }
            break;
        case 0x1b:
            let sourceId = dataView.getUint8(3);
            //数据源信息
            const sourceBuffer = Buffer.from(uint8Array.slice(4, -1));
            // 将 Buffer 转换为字符串
            const sourceName = sourceBuffer.toString('utf8');
            const sourceData = {
                value: sourceId,
                label: sourceName
            }
            console.log('数据源信息:' + sourceId, sourceName)
            store.dispatch('battery/setSourceData', sourceData)
            break;
        case 0x11:
            //当前设备数据源
            const curSourceId = dataView.getUint8(3);
            console.log('当前设备数据源', curSourceId)
            update = {
                curSourceId
            }
            break;
        case 0x0e:
            //保护板蓝牙
            let currentIndex = 3;
            const macAddress = [];
            for (let j = 0; j < 6; j++) {
                macAddress.push(dataView.getUint8(currentIndex + j).toString(16).padStart(2, '0'))
            }
            const formattedMacAddress = macAddress.join(':')
            const nameBuffer = uint8Array.slice(9, -1).buffer
            // 使用TextDecoder进行解码
            var name = new encoding.TextDecoder().decode(nameBuffer)
            console.log(`保护板码表绑定信息：${name}-${formattedMacAddress}`)
            update = {
                protectBluetoothName: name,
                protectBluetoothMac: formattedMacAddress
            }
            break;
        case 0x10:
            console.log("扫描到的数据")
            let curIndex = 3;
            let smacAddress = [];
            for (let j = 0; j < 6; j++) {
                smacAddress.push(dataView.getUint8(curIndex + j).toString(16).padStart(2, '0'))
            }
            const sFormattedMacAddress = smacAddress.join(':')
            const scanBuffer = uint8Array.slice(9, -1).buffer
            // 使用TextDecoder进行解码
            var scanName = new encoding.TextDecoder().decode(scanBuffer)
            uni.$emit('syncBluetoothList', {
                name: scanName,
                macAddress: sFormattedMacAddress
            })
            break;
        }
        store.dispatch('battery/setBatteryData', update)

    }
}

export function onBLEConnectionStateChange(res) {
    console.log(res)
    let batteryData = store.getters['battery/batteryData']
    if (batteryData?.deviceId == res.deviceId) {
        store.dispatch('battery/setBatteryData', {
            connected: res.connected
        })
        store.dispatch('battery/clearData')
    }
}

export function getModelName(type, val) {
    let list = []
    switch (type) {
    case 'vehicleType':
        list = store.getters['battery/vehicleTypeData']
        break
    case 'batteryType':
        list = batteryTypeList
        break
    }
    const res = list.find(item => {
        return item.value == val
    })
    // console.log('名称解析:' + type, res)
    return res !== undefined ? res.label : '未知'

}

export function readFileContent(filePath) {
    const fileSystemManager = uni.getFileSystemManager();
    return new Promise((resolve, reject) => {
        fileSystemManager.readFile({
            filePath: filePath,
            // encoding: 'utf8',
            success: (res) => {
                // 这里的 res.data 包含了文件的内容
                resolve(res.data)
            },
            fail: (err) => {
                console.error('Read file failed:', err);
                reject(err)
            }
        });
    })

}